import axios from "axios";
import config from "./config.js";

class Api {
  server;
  constructor() {
    this.server = axios.create({
      baseURL: config.baseUrl.dev,
      timeout: 3000,
      withCredentials: false,
      headers: {
        "X-Custom-Header": "foobar",
      },
    });
    this.server.interceptors.request.use(
      (config) => {
        let token = localStorage.getItem("token");
        console.log(token);
        if (token !== null && token !== undefined) {
          // eslint-disable-next-line no-param-reassign
          config.headers = {
            ...config.headers,
            Authorization: token,
          };
        } else {
          // eslint-disable-next-line no-param-reassign
          config.headers = {
            ...config.headers,
          };
        }
        if (
          config.data instanceof FormData &&
          token !== null &&
          token !== undefined
        ) {
          // eslint-disable-next-line no-param-reassign
          config.headers = {
            ...config.headers,
            "Content-Type": "multipart/form-data",
            Authorization: token,
          };
        }
        return config;
      },
      function (err) {
        return Promise.reject(err);
      }
    );
    this.server.interceptors.response.use(
      (response) => {
        let token = response.headers.authorization;
        if (token !== undefined) {
          localStorage.setItem("token", token);
        }
        return response;
      },
      function (err) {
        return Promise.reject(err);
      }
    );
  }

  connection(method = "get", url, body) {
    let data = null;
    if (method === "get" || method === "delete") {
      data = async (resolve, reject) => {
        try {
          const result = await this.server({
            method: method,
            url: url,
            params: body,
          });
          resolve(result.data);
        } catch (err) {
          reject(err.toString());
        }
      };
    } else {
      data = async (resolve, reject) => {
        try {
          const result = await this.server({
            method: method,
            url: url,
            data: body,
          });
          resolve(result.data);
        } catch (err) {
          reject(err.toString());
        }
      };
    }
    return new Promise(data);
  }
}

const request = new Api();
export default request;
